'use strict';

const db = uniCloud.database()
const postsCollection = db.collection('posts')

exports.main = async (event, context) => {
	try {
		const { postId, title, content, images = [] } = event
		
		// 参数验证
		if (!postId) {
			return {
				code: -1,
				msg: '帖子ID不能为空',
				data: null
			}
		}
		
		if (!title) {
			return {
				code: -1,
				msg: '标题不能为空',
				data: null
			}
		}
		
		if (!content) {
			return {
				code: -1,
				msg: '内容不能为空',
				data: null
			}
		}
		
		// 获取当前用户信息
		const userInfo = event.userInfo
		if (!userInfo) {
			return {
				code: -1,
				msg: '用户未登录',
				data: null
			}
		}
		
		// 检查帖子是否存在
		const post = await postsCollection.doc(postId).get()
		if (!post.data || post.data.length === 0) {
			return {
				code: -1,
				msg: '帖子不存在',
				data: null
			}
		}
		
	
		
		// 更新帖子
		const updateData = {
			title,
			content,
			images,
			updateTime: Date.now()
		}
		
		await postsCollection.doc(postId).update(updateData)
		
		return {
			code: 0,
			msg: '更新成功',
			data: null
		}
	} catch (error) {
		console.error('更新帖子失败', error)
		return {
			code: -1,
			msg: '更新失败',
			data: null
		}
	}
} 